/**
 * promise.all 需要实现的就是，多个异步请求一起返回请求的数据。
 * 思路：获取异步任务的个数，利用promise获取每一个异步任务的结果，用一个数组承接，等异步任务处理完以后，返回该数组。
 * @param {*} iterator
 * @returns
 */
const PromiseAll = (iterator) => {
  const promises = Array.from(iterator); // 浅拷贝，确保promises可遍历
  const len = promises.length;
  let data = [];
  return new Promise((resolve, reject) => {
    for (let i = 0; i < len; i++) {
      promises[i]
        .then((res) => {
          data[i] = res;
          if (i === promises.length - 1) {
            resolve(data);
          }
        })
        .catch((err) => {
          reject(err);
        });
    }
  });
};

const promise1 = Promise.resolve("promise1");
const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve("promise2"), 2000);
});
const promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve("promise3"), 1000);
});

PromiseAll([promise1, promise2, promise3]).then((res) => {
  console.log(res);
});

Promise.all([promise1, promise2, promise3]).then((res) => {
  console.log(res);
});
